﻿using OrderingFoot.Core;
using Microsoft.EntityFrameworkCore;

namespace OrderingFoot.DbContextCore
{
    /// <summary>
    /// dbcontext
    /// </summary>
    public class OrderingFootDbContext : BaseDbContext<OrderingFootDbContext>
    {
        private readonly ICurrentInfo _currentInfo;
        /// <summary>
        /// ctor
        /// </summary>
        public OrderingFootDbContext(
            DbContextOptions options,
            ICurrentInfo currentInfo) : base(options)
        {
            _currentInfo = currentInfo;
        }

        /// <summary>
        /// 实体模型配置
        /// </summary>
        /// <param name="modelBuilder">ModelBuilder</param>
        public override void OnModelCreate(ModelBuilder modelBuilder)
        {
            modelBuilder.ApplyConfigurationsFromAssembly(GetType().Assembly);
        }

        /// <summary>
        /// SaveChangesAsync
        /// </summary>
        public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default)
        {
            foreach (var item in ChangeTracker.Entries())
            {
                if (item.Entity is BaseEntity entity)
                {
                    if (item.State == EntityState.Added)
                    {
                        entity.CreateTime = DateTimeOffset.Now;
                        entity.UpdateTime = DateTimeOffset.Now;
                        entity.CreateBy = _currentInfo?.UserName ?? string.Empty;
                    }
                    else if (item.State == EntityState.Modified)
                    {
                        entity.UpdateTime = DateTimeOffset.Now;
                        entity.UpdateBy = _currentInfo?.UserName ?? string.Empty;
                    }
                }
            }

            return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
        }
    }
}
